// node ./imagesToBase64Array.js ./src/data/ ./src/img/test/
var fs = require('fs');

var rootPath = process.argv[2];
var videoName = process.argv[3];
var targetFilePath = process.argv[4];
var jsList = [];


function writeIn(filelist) {

	fs.stat(targetFilePath, function(err, stats) {
		if (stats.isFile()) {
			// console.log(stats);
			fs.open(targetFilePath, 'r+', 0644, function(err, fd) {
				if (err) throw err;
				var textBuffer = new Buffer(stats.size);
				fs.read(fd, textBuffer, 0, stats.size, 0, function(err, bytesRead, buffer) {
					if (err) throw err;

					var afterText = buffer.toString();

					var LoadStr = [];

					LoadStr.push('\<div style=\"display: none;\" id=\"Loader\"\>');
					for (var i = 0; i < filelist.length; i++) {
						LoadStr.push('\n\r\<img data-src=\"' + filelist[i] + '\"\>');
					}
					LoadStr.push('\n\r\<\/div\>')
					afterText = afterText.replace(/\<\/body\>/ig, LoadStr.join('') + '\n\r\<\/body\>')

					fs.writeFile(targetFilePath, afterText, function(err) {
						if (err) throw err;
						console.log('写入'+ targetFilePath +'文件成功');
					})
				})
			})
		}
	})

}

function findDirDeep(path, name) {
	var fileArray = [];

	fs.readdirSync(path).forEach(function(file) {

		var pathName = path + '/' + file;


		var stats = fs.statSync(pathName);

		if (stats.isFile()) {

			if (/.*\.(png|jpg|gif|bmp)/ig.test(file)) {

				fileArray.push("\'data:image/png;base64," + new Buffer(fs.readFileSync(pathName)).toString('base64') + "\'");
			}

		} else if (stats.isDirectory()) {


			findDirDeep(pathName, file)

		}
	});


	// console.log(videoName + '/' +name,fileArray.length);
	if (fileArray.length) {

		// fs.mkdirSync(videoName);

		var fileText = ';window.' + name + '=\[' + fileArray.join(',') + '\];';

		var filepath = (videoName + '/' + name + '.js').replace(/\/\//ig,'/');

		jsList.push(filepath);
		fs.open(videoName + '/' + name + '.js', "w+", 0644, function(e, fd) {
			if (e) throw e;
			fs.write(fd, fileText, 0, 'utf8', function(e) {
				if (e) throw e;

				console.log('成功创建文件 ： ' + videoName + '/' + name + '.js');
				fs.closeSync(fd);
			})
		});
	}


}

if (!rootPath) {
	console.log('请选择文件目录');

} else if (!videoName) {
	console.log('请指定文件名');

} else {
	var s = fs.mkdir(videoName, function(err, callback) {
		findDirDeep(rootPath, '');

		if(jsList.length && targetFilePath){
			writeIn(jsList)
		}
	});
}